<template>
  <div class="publish-container">
    <el-card>
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{
            isEdit ? "编辑文章" : "发布文章"
          }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form ref="form" :rules="rules" :model="article" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="article.title"></el-input>
        </el-form-item>
        <!-- 内容编辑器 -->
        <el-form-item label="内容" prop="content" class="editor">
          <quillEditor v-model="article.content" :options="editorOption" />
        </el-form-item>
        <el-form-item label="封面">
          <el-radio-group v-model="article.cover.type">
            <!-- 根据后端接口约定 -->
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 选择素材 -->
        <!-- 根据article.cover.type值决定选择素材数量 -->
        <el-form-item class="sel-img" v-if="article.cover.type > 0">
          <el-simg
            v-for="(img, i) in article.cover.type"
            :selImg.sync="article.cover.images[i]"
            :key="img"
          />
        </el-form-item>

        <el-form-item label="频道" prop="channel_id">
          <el-select v-model="article.channel_id" placeholder="请选择活动区域">
            <el-option
              v-for="channel in channels"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addArticle(false)">{{
            isEdit ? "编辑" : "发表"
          }}</el-button>
          <el-button @click="addArticle(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
// 导入频道/创建文章后台接口
// eslint-disable-next-line no-unused-vars
import { getChannel, createArticle, getArticleDetail, updateArticle } from '@/api/news'
// 导入编辑器组件和样式
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 导入选择文章封面子组件
import ElSimg from './components/selImg'

export default {
  components: {
    quillEditor,
    ElSimg
  },
  data () {
    return {
      // 判断是发布/编辑状态
      isEdit: false,
      // 频道列表
      channels: [],
      // 发布文章表单数据
      article: {
        title: '', // 文章标题
        content: '', // 文章内容
        cover: {
          type: 0, // 封面图片的张数
          images: [] // 封面的地址
        },
        channel_id: '' // 频道id
      },
      // 验证规则
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 5, max: 30, message: '长度在5到30之间', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' },
          { min: 20, message: '最少20个字', trigger: 'blur' }
        ],
        channel_id: [
          { required: true, message: '请选择文章频道', trigger: 'blur' }
        ]
      },
      // 文本编辑器展示配置
      editorOption: {
        placeholder: '请输入文章内容', // 占位文字
        modules: {
          // 工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image', 'video']
          ]
        }
      }
    }
  },
  // watch: {
  //   '$route.path': {
  //     handler () {
  //       console.log(this.$route.path)
  //       // 获取文章ID
  //       console.log(this.$route.params.id)
  //       if (this.$route.params.id) {
  //         // 文章编辑
  //         this.isEdit = true
  //         this.article.title = Math.random() * 1000
  //       } else {
  //         this.isEdit = false
  //       }
  //     },
  //     immediate: true
  //   }
  // },
  created () {
    console.log(123)
    this.getChannels()
    // 获取文章ID
    console.log(this.$route.params.id)
    if (this.$route.params.id) {
      // 文章编辑
      this.isEdit = true
      // 编辑状态：获取文章详情数据=》渲染
      this.getArticleDetail()
    }
  },
  methods: {
    // 获取文章详情
    async getArticleDetail () {
      const { data: { data } } = await getArticleDetail(this.$route.params.id)
      this.article = data
    },
    // 获取频道列表
    async getChannels () {
      const { data } = await getChannel()
      // console.log(data)
      this.channels = data.data.channels
    },
    // 发表文章
    addArticle (isDraft) {
      this.$refs.form.validate(async (valid) => {
        // console.log(valid)
        if (valid) {
          // 全部校验通过
          try {
            // 是否是草稿发布
            const params = {
              draft: isDraft
            }
            // 判断是发表/编辑
            if (this.isEdit) {
              // 编辑文章
              await updateArticle(this.$route.params.id, params, this.article)
              this.$message({
                message: '文章修改成功！', type: 'success'
              })
            } else {
              // 发表文章逻辑
              await createArticle(params, this.article)
              this.$message({
                message: '文章发表成功！', type: 'success'
              })
            }

            // 跳转到文章列表页
            this.$router.push('/articles')
          } catch (error) {
            this.$message('操作失败！')
          }
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.selimg-container {
  background: red;
}
.editor {
  /deep/ .el-form-item__content {
    line-height: normal;
  }
}

// 文章封面图样式
// 处理图片选择框水平显示
.sel-img /deep/ .el-form-item__content {
  display: flex;
  .selimg-container {
    margin-right: 20px;
  }
}

/deep/ .sel-box {
  border-radius: 10px;
}
</style>
